#coding=utf-8
import sys

from uliweb.orm import get_model, set_dispatch_send, Begin, Commit, Rollback

set_dispatch_send(False)
#注意日期行的换行
def call(args, options, global_options):
    from uliweb.core.SimpleFrame import get_apps, get_app_dir, Dispatcher
    from uliweb.utils.common import log
    
    app = Dispatcher(apps_dir=global_options.apps_dir, start=False)
    Begin()
    try:
        if len(args) != 2:
            print "Usage: uliweb call import_riskpoint_task riskpoint.xls"
            sys.exit(1)
            
        process(args, options, global_options)
        Commit()
    except Exception, e:
#        print '----------',row
        log.exception(e)
        Rollback()
        import traceback
        traceback.print_exc()

def process(args, options, global_options):
    from uliweb.orm import get_model
    from parse_excel import open_book
    
    
    Risk = get_model('riskpoint')
    System = get_model('system')
    Kfzx = get_model('kfzx')
    Requirement = get_model('requirement')
    Tasks_develop = get_model('tasks_develop')
    
    error_log = open('riskpoint_log_finishdate.txt','w')
    
    Risk.modified_user.default = None
    #更新计划完成时间
    fields = ['check_id','plan_finish_date']

    
#    fields = ['1', '2', 'mqc_id', '4', 'system', 'check_id', 'risk_obj', 
#        'risk_desc', 'risk_analysis', ('level', 'PARA/RISK_LEVEL'), 'policy', '12', '13',
#        '14', '15', '16', '17', '18', '19', '20', '21', '22', 'reform_type',
#        'reform_measure', 'answer_policy', ('urgent_degree', 'PARA/URGENT_DEGREE'), 
#        '_', '_', '_',
#        'plan_finish_date', '_', 'lead_tx', 'kfzx', '_', '_', '_', '_']
    
    kfzx = {
        u'深圳个贷支持中心':'7', 
        u'北京开发中心':'1',
        u'上海开发中心':'2',
        u'武汉开发中心':'6',
        u'成都开发中心':'5',
        u'厦门开发中心':'3',
        u'广州开发中心':'4',
        u'香港支持中心':'8',
        }
        
#    tx = {
#        '安全管理条线':'',
#        '北京数据中心':'',
#        '
#    }
    
    def get_key(key, value):
        """
        用于反向根据值来获取key，如[('1', '高'), ('2', '低')]，根据'高'得到'1'
        """
        from uliweb import settings
        
        s = settings.get_var(key, [])
        for k, v in s:
            if isinstance(value, unicode):
                value = value.encode('utf-8')
            if isinstance(v, unicode):
                v = value.encode('utf-8')
                
            if value == v:
                return k
    
    f = {}
    c = {}
    for i, item in enumerate(fields):
        if isinstance(item, (tuple, list)):
            c[item[0]] = item[1]
            f[i] = item[0]
        else:
            f[i] = item

    n = 1
    m = 1
    for line in open_book(args[1], begin=0, fields=f):
        d = line.copy()
#        d['mqc_id'] = str(int(d['mqc_id']))
        #process value convert
        for k, v in c.iteritems():
            if k in d:
                d_v = d[k]
                d[k] = get_key(v, d_v)
                
           
        if d['check_id']:
            row = Risk.get(Risk.c.check_id==d['check_id'])
            if row:
#                s_error = u"------:[%s],行号: %d [%s]\n" % (d['check_id'], n,d)
#                error_log.write(s_error.encode('gbk'))
                
                row.update(**d)
                row.save()
                m += 1
##                s_error = u"整改事项序号已更新:[%s],行号: %d \n" % (d['check_id'], n)
##                error_log.write(s_error.encode('gbk'))
            else:
#                print '+++++++',d['check_id']
                s_error = u"整改事项未找到，序号:[%s],行号: %d \n" % (d['check_id'], n)
                error_log.write(s_error.encode('gbk'))
                
#                row = Risk(**d)
#            row.save()
            n += 1
        else:
            s_error = u"整改事项序号为空:[%s],行号: %d \n" % (d['check_id'], n)
            error_log.write(s_error.encode('gbk'))
            n += 1
            continue
        
        
    print 'Total %d records processed,finished %d' % (n,m)
        
